package kr.hyosang.dkbs.kiosk.widget;

import java.io.ByteArrayInputStream;
import java.nio.charset.Charset;
import java.util.ArrayList;

import javafx.application.Platform;
import javafx.scene.control.Label;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import kr.hyosang.util.NetManager;
import kr.hyosang.util.NetManager.RequestType;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

public class BusInfo extends WidgetBase {
	private class BusStop {
		public String stopSeq;
		public String stopNo;
		public String stopName;
		public String currentBusNo;
	}
	
	private class BeforeStop {
		public int nCount = 0;
		public BusStop stop = null;
	}
	
	private final String BASE_STOP_NO = "1478";	//단국대학교
	private enum Route {DUJUNG, TERMINAL};
	private ImageView imgBusIcon;
	private Label lblDujung;
	private Label lblTerminal;
	
	public BusInfo(ImageView icon, Label dujung, Label terminal) {
		imgBusIcon = icon;
		lblDujung = dujung;
		lblTerminal = terminal;
		
		ClassLoader cl = BusInfo.class.getClassLoader();
		imgBusIcon.setImage(new Image(cl.getResourceAsStream("image/bus.png")));
		
		String backImg = cl.getResource("image/gray_back.png").toExternalForm();
		String backStyle = String.format("-fx-background-image:url('%s');", backImg);
		lblDujung.getParent().setStyle(backStyle);
		lblTerminal.getParent().setStyle(backStyle);
		
		lblDujung.setText("조회중...");
		lblTerminal.setText("조회중...");
		
		
		mGatherInfo.start();
	}

	@Override
	protected String getTag() {
		return "BusInfo";
	}
	
	private Thread mGatherInfo = new Thread() {
		@Override
		public void run() {
			while(true) {
				try {
					final String strDj = getInfoString(Route.DUJUNG);
					final String strTm = getInfoString(Route.TERMINAL);
					
					Platform.runLater(new Runnable() {
						@Override
						public void run() {
							lblDujung.setText(strDj);
							lblTerminal.setText(strTm);
						}
					
					});
					
					Thread.sleep(60 * 1000);	//60s
				}catch(Exception e) {
					log(e.getMessage());
				}
			}
		}
	};
	
	private String getInfoString(Route route) {
		ArrayList<BusStop> stopList = getBusInfo(route);
		
		if(stopList != null) {
			BeforeStop beforeStop = null;
			int nBaseIdx = -1;
			for(int i=0;i<stopList.size();i++) {
				if(BASE_STOP_NO.equals(stopList.get(i).stopNo)) {
					nBaseIdx = i;
					break;
				}
			}
			
			if(nBaseIdx != -1) {
				//역방향 검색
				for(int i=nBaseIdx;i>=0;i--) {
					BusStop stop = stopList.get(i);
					if(stop.currentBusNo != null && !stop.currentBusNo.isEmpty()) {
						BeforeStop bs = new BeforeStop();
						bs.nCount = nBaseIdx - i;
						bs.stop = stop;
						beforeStop = bs;
						
						break;
					}
				}
			}
			if(beforeStop != null) {
				if(beforeStop.nCount == 0) {
					return String.format("%s 정류장 도착", beforeStop.stop.stopName);
				}else {
					return String.format("%d 정류장 전 %s", beforeStop.nCount, beforeStop.stop.stopName);
				}
			}
		}
		
		return "정보 없음";
	}
	
	private ArrayList<BusStop> getBusInfo(Route route) {
		try {
			//두정역 : route_no=5, route_class=1
			//터미널 : route_no=5, route_class=2
			
			String postBody = "route_no=5";
			if(route == Route.DUJUNG) {
				postBody += "&route_class=1";
			}else if(route == Route.TERMINAL) {
				postBody += "&route_class=2";
			}
			
			String body = NetManager.getWebContent(
					"http://its.cheonan.go.kr/include/bis/RouteStation.jsp",
					RequestType.POST,
					Charset.forName("UTF-8"),
					postBody,
					Charset.forName("UTF-8")
					);
			
			if(!body.startsWith("<?")) {
				body = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" + body;
			}
			
			DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
			DocumentBuilder builder = factory.newDocumentBuilder();
			Document document = builder.parse(new InputSource(new ByteArrayInputStream(body.getBytes("utf-8"))));
			Node rootNode = document.getFirstChild();
			
			NodeList nodeList = rootNode.getChildNodes();
			
			ArrayList<BusStop> stopList = new ArrayList<BusStop>();

			
			for(int i=0;i<nodeList.getLength();i++) {
				Node node = nodeList.item(i);
				if(node.getNodeType() == Node.ELEMENT_NODE) {
					NodeList itemNodes = node.getChildNodes();
					BusStop stop = new BusStop();
					
					for(int j=0;j<itemNodes.getLength();j++) {
						Node itemNode = itemNodes.item(j);
						if(itemNode.getNodeType() == Node.ELEMENT_NODE) {
							if("stop_name".equals(itemNode.getNodeName())) {
								stop.stopName = getNodeValue(itemNode);
							}else if("stop_seq".equals(itemNode.getNodeName())) {
								stop.stopSeq = getNodeValue(itemNode);
							}else if("bus_name".equals(itemNode.getNodeName())) {
								stop.currentBusNo = getNodeValue(itemNode);
							}else if("stop_no".equals(itemNode.getNodeName())) {
								stop.stopNo = getNodeValue(itemNode);
							}
						}
					}
					
					if(stop.stopName != null && !stop.stopName.isEmpty()) {
						stopList.add(stop);
					}
					
					
				}
			}
			
			return stopList;
		
		}catch(Exception e) {
			log(e.getMessage());
		}
		
		
		return null;
		
	}

	
	private String getNodeValue(Node node) {
		if(node != null) {
			if(node.hasChildNodes()) {
				String val = node.getFirstChild().getNodeValue();
				if(val != null) {
					val = val.trim();
					if("null".equals(val)) {
						return null;
					}else {
						return val;
					}
				}
			}
		}
		return null;
	}

}
